﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Wyse.Server.Common
{
    /// <summary>
    /// Singleton template
    /// </summary>
    public class Singleton<T> where T : class, new()
    {
        /// <summary>
        /// Gets the instance of the singleton
        /// </summary>
        public static T Instance
        {
            get { return sInstance; }
        }

        private static T sInstance = new T();
    }

    /// <summary>
    /// Synchronized template
    /// </summary>
    public class SyncSingleton<T> : IDisposable where T : class, new()
    {
        /// <summary>
        /// Locks the singleton's instance
        /// </summary>
        /// <returns></returns>
        public static T LockInstance()
        {
            Monitor.Enter(sInstance);
            return sInstance;
        }

        /// <summary>
        /// Locks the singleton's instance
        /// </summary>
        /// <returns></returns>
        public static T LockInstance(TimeSpan timeout)
        {
            if (!Monitor.TryEnter(sInstance, timeout))
                throw new TimeoutException();
            return sInstance;
        }

        /// <summary>
        /// Unlocks the singleton's instance
        /// </summary>
        public void UnlockInstance()
        {
            Monitor.Exit(sInstance);
        }

        public void Dispose()
        {
            UnlockInstance();
        }

        private static T sInstance = new T();
    }
}
